package http.ach;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

// 用于响应请求
public class HttpResponse {
    // 响应状态码
    private int status;

    //响应信息
    private String message;

    // 响应头
    private Map<String,String> headers = new HashMap<>();

    // 输出 媒介
    private BufferedWriter bufferedWriter;

    // 统一编码
    private static final String CHARSET = "UTF-8";

    // 响应 body
    private StringBuilder body = new StringBuilder();

    // 工厂 方法 返回一个 HttpResponse 对象
    public static HttpResponse build(OutputStream outputStream) throws UnsupportedEncodingException {
        HttpResponse response = new HttpResponse();
        response.bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,CHARSET));
        // TODO 根据具体业务逻辑进行预处理 现在不处理
        return response;
    }

    public void flush() throws IOException {
        bufferedWriter.write("HTTP/1.1 "+status+" "+ message +"\n");
        bufferedWriter.write("Content-Type: text/html; charset=utf-8\n");
        bufferedWriter.write("Content-Length: "+body.toString().getBytes().length+"\n");
        headers.forEach((K,V)->{
            try {
                bufferedWriter.write(K+": "+V+"\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        bufferedWriter.write("\n");
        bufferedWriter.write(body.toString());
        bufferedWriter.flush();
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getHeaders(String key) {
        return headers.get(key);
    }

    public void setHeaders(String key,String value) {
        this.headers.put(key,value);
    }

    public BufferedWriter getBufferedWriter() {
        return bufferedWriter;
    }

    public void setBufferedWriter(BufferedWriter bufferedWriter) {
        this.bufferedWriter = bufferedWriter;
    }

    public static String getCHARSET() {
        return CHARSET;
    }

    public StringBuilder getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body.append(body);
    }
}
